<template>
  <div class="layout-padding">
    <div class="layout-padding-auto layout-padding-view">
      <!-- 查询表单区域 -->
      <el-row v-show="showSearch">
        <el-form :model="state.queryForm" ref="queryRef" :inline="true" @keyup.enter="getDataList">
          <el-form-item label="设备编号" prop="deviceSn">
            <el-input
              placeholder="请输入设备编号"
              v-model="state.queryForm.deviceSn"
            />
          </el-form-item>
          <el-form-item label="设备名称" prop="deviceName">
            <el-input
              placeholder="请输入设备名称"
              v-model="state.queryForm.deviceName"
            />
          </el-form-item>
          <el-form-item label="归属用户账号" prop="username">
            <el-input
              placeholder="请输入归属用户账号"
              v-model="state.queryForm.username"
            />
          </el-form-item>
          <el-form-item label="归属用户姓名" prop="name">
            <el-input
              placeholder="请输入归属用户姓名"
              v-model="state.queryForm.name"
            />
          </el-form-item>
          <el-form-item>
            <el-button icon="search" type="primary" @click="getDataList">
              查询
            </el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <!-- 操作按钮区域 -->
      <el-row>
        <div class="mb8" style="width: 100%">
          <el-button
            icon="folder-add"
            type="primary"
            class="ml10"
            @click="formDialogRef.openDialog()"
            v-auth="'admin_deviceInfo_add'"
          >
            新增
          </el-button>
<!--          <el-button-->
<!--            plain-->
<!--            icon="upload-filled"-->
<!--            type="primary"-->
<!--            class="ml10"-->
<!--            @click="excelUploadRef.show()"-->
<!--            v-auth="'admin_deviceInfo_add'"-->
<!--          >-->
<!--            导入-->
<!--          </el-button>-->
          <el-button
            plain
            :disabled="multiple"
            icon="Delete"
            type="primary"
            v-auth="'admin_deviceInfo_del'"
            @click="handleDelete(selectObjs)"
          >
            删除
          </el-button>
          <right-toolbar
            v-model:showSearch="showSearch"
            :export="'admin_deviceInfo_export'"
            @exportExcel="exportExcel"
            class="ml10 mr20"
            style="float: right;"
            @queryTable="getDataList"
          />
        </div>
      </el-row>

      <!-- 数据表格区域 -->
      <el-table
        :data="state.dataList"
        v-loading="state.loading"
        border
        :cell-style="tableStyle.cellStyle"
        :header-cell-style="tableStyle.headerCellStyle"
        @selection-change="selectionChangHandle"
        @sort-change="sortChangeHandle"
      >
        <el-table-column type="selection" width="40" align="center" />
        <el-table-column type="index" label="#" width="40" />
        <el-table-column
          prop="deviceSn"
          label="设备编号"
          show-overflow-tooltip
        />
        <el-table-column
          prop="deviceName"
          label="设备名称"
          show-overflow-tooltip
        />
        <el-table-column prop="protocol" label="上报协议" show-overflow-tooltip />
        <el-table-column prop="measureDistance" label="设备量程" show-overflow-tooltip />
        <el-table-column
          prop="username"
          label="归属用户账号"
          show-overflow-tooltip
        />
        <el-table-column
          prop="name"
          label="归属用户姓名"
          show-overflow-tooltip
        />
        <el-table-column width="90" prop="deviceOnlineStatus" label="是否在线">
          <template #default="{ row }">
            <span :class="row.deviceOnlineStatus == 1 ? 'text-green-400' : ''">
              {{ row.deviceOnlineStatus == 1 ? '是' : '否' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column width="90" prop="alarmFlag" label="是否报警">
          <template #default="{ row }">
            <span :class="{'text-red-400' : row.alarmFlag == 1 }">
              {{ row.alarmFlag == 1 ? '是' : '否' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column width="90" prop="battStr" label="电量"></el-table-column>
        <el-table-column
          prop="remark"
          label="备注"
          show-overflow-tooltip
        />
        <el-table-column label="操作" width="190">
          <template #default="scope">
            <el-button
              icon="edit-pen"
              text
              type="primary"
              v-auth="'admin_deviceInfo_edit'"
              @click="formDialogRef.openDialog(scope.row.deviceId)"
            >
              编辑
            </el-button>
            <el-button
              icon="location"
              text
              type="primary"
              v-auth="'admin_deviceInfo_edit'"
              @click="handleLocation(scope.row.deviceId)"
            >
              位置
            </el-button>
            <el-button
              icon="delete"
              text
              type="primary"
              v-auth="'admin_deviceInfo_del'"
              @click="handleDelete([scope.row.deviceId])"
            >
              删除
            </el-button>
            <el-button
              icon="operation"
              text
              type="warning"
              v-auth="'admin_deviceInfo_edit'"
              @click="handleCmd(scope.row)"
            >
              命令下发
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <pagination
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        v-bind="state.pagination"
      />
    </div>

    <!-- 编辑、新增弹窗 -->
    <form-dialog ref="formDialogRef" @refresh="getDataList(false)" />

    <!-- 导入excel弹窗 (需要在 upms-biz/resources/file 下维护模板) -->
    <upload-excel
      ref="excelUploadRef"
      title="导入"
      url="/admin/deviceInfo/import"
      temp-url="/admin/sys-file/local/file/deviceInfo.xlsx"
      @refreshDataList="getDataList"
    />

    <el-dialog title="设备位置详情" v-model="locationVisible" draggable>
      <Map v-if="locationVisible" :center="locationCenter"></Map>
    </el-dialog>

    <el-dialog title="设备命令下发" v-model="cmdVisible" width="400px" :destroy-on-close="true" draggable>
      <el-form :model="cmdForm" :rules="cmdRules" ref="cmdFormRef">
        <el-form-item label="设备名称" prop="deviceName">
          {{ cmdForm.deviceName }}
        </el-form-item>
        <el-form-item label="设备Sn" prop="deviceSn">
          {{ cmdForm.deviceSn }}
        </el-form-item>
        <el-form-item label="命令" prop="sendMsg">
          <el-input v-model="cmdForm.sendMsg" placeholder="请输入命令" />
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="cmdVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitCmd">确 定</el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="systemDeviceInfo">
// ========== 导入声明 ==========
import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList, delObjs, getLocation } from "/@/api/admin/deviceInfo";
import { useMessage, useMessageBox } from "/@/hooks/message";
import { useDict } from '/@/hooks/dict';
import Map from './map.vue';
import { addObj as addCmdObj } from '/@/api/deviceCmd/deviceCmd';

// ========== 组件声明 ==========
// 异步加载表单弹窗组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));

// ========== 字典数据 ==========

// ========== 组件引用 ==========
const formDialogRef = ref();          // 表单弹窗引用
const excelUploadRef = ref();         // Excel上传弹窗引用
const queryRef = ref();               // 查询表单引用

// ========== 响应式数据 ==========
const showSearch = ref(true);         // 是否显示搜索区域
const selectObjs = ref([]) as any;    // 表格多选数据
const multiple = ref(true);           // 是否多选

// ========== 表格状态 ==========
const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: {},    // 查询参数
  pageList: fetchList // 分页查询方法
});

// ========== Hook引用 ==========
// 表格相关Hook
const {
  getDataList,
  currentChangeHandle,
  sizeChangeHandle,
  sortChangeHandle,
  downBlobFile,
  tableStyle
} = useTable(state);

// ========== 方法定义 ==========
/**
 * 重置查询条件
 */
const resetQuery = () => {
  // 清空搜索条件
  queryRef.value?.resetFields();
  // 清空多选
  selectObjs.value = [];
  // 重新查询
  getDataList();
};

/**
 * 导出Excel文件
 */
const exportExcel = () => {
  downBlobFile(
    '/admin/deviceInfo/export',
    Object.assign(state.queryForm, { ids: selectObjs }),
    'deviceInfo.xlsx'
  );
};

/**
 * 表格多选事件处理
 * @param objs 选中的数据行
 */
const selectionChangHandle = (objs: { deviceId: string }[]) => {
  selectObjs.value = objs.map(({ deviceId }) => deviceId);
  multiple.value = !objs.length;
};

/**
 * 删除数据处理
 * @param ids 要删除的数据ID数组
 */
const handleDelete = async (ids: string[]) => {
  try {
    await useMessageBox().confirm('此操作将永久删除');
  } catch {
    return;
  }

  try {
    await delObjs(ids);
    getDataList();
    useMessage().success('删除成功');
  } catch (err: any) {
    useMessage().error(err.msg);
  }
};

// 查看设备位置
const locationVisible = ref(false);
const locationCenter = ref<number[]>([]);
const handleLocation = (deviceId: string) => {
  getLocation({ deviceId }).then((res: any) => {
    if (res.code == 0 && res.data[0]) {
      useMessage().success('查询成功');
      locationCenter.value = [res.data[0].lon, res.data[0].lat];
      locationVisible.value = true;
    } else {
      useMessage().error('未查询到该设备位置');
    }
  });
}

// 命令下发
const cmdVisible = ref(false);
const cmdForm = ref<any>({ sendMsg: '' });
const cmdRules = {
  sendMsg: [{ required: true, message: '请输入命令', trigger: 'blur' }]
};
const cmdFormRef = ref();
const handleCmd = (deviceObj: any) => {
  cmdVisible.value = true;
  cmdForm.value = {
    sendMsg: '',
    deviceId: deviceObj.deviceId,
    deviceName: deviceObj.deviceName,
    deviceSn: deviceObj.deviceSn,
    status: '0'
  }
}
const submitCmd = async () => {
  await cmdFormRef.value.validate();
  try {
    await addCmdObj(cmdForm.value);
    useMessage().success('命令下发成功');
    cmdVisible.value = false;
    getDataList();
  } catch (err: any) {
    useMessage().error(err.msg);
  }
}
</script>
